import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import {
  operateDemand,
  cancelOperateDemand,
  fetchDemandDetail,
  operateCollect,
  operateCancelCollect,
} from '@/business/services/demand/demand';
import { demandListStore } from '@/business/store/demand/demandList';
import { myColletionStore } from '@/business/store/myColletion/index';
import { searchStore } from '@/business/store/search/search';

/**
 * @description 需求详情
 * @author Shawn
 */

type RequestFunction = (id: string) => Promise<void>;

type RequestFunction2 = (demandId: string, type: string, status: string) => Promise<void>;

type RequestFunction3 = (demandId: string) => Promise<void>;

type State = {
  // 需求详情
  demandDetail: any;
  // 数据是否加载完成
  isDataLoaded: boolean;
};

type Actions = {
  // 获取需求详情
  getDemandDetail: RequestFunction;
  // 点赞、点踩
  handleLikeOrDislike: RequestFunction2;
  // 取消点赞、点踩
  handleCancelLikeOrDislike: RequestFunction2;
  // 收藏
  handleCollect: RequestFunction2;
  // 取消收藏
  handleCancelCollect: RequestFunction3;

  clear: () => void;
};

const initialState: State = {
  demandDetail: {},
  isDataLoaded: true,
};

export const demandDetailStore = create<State & Actions>()(
  immer((set) => ({
    ...initialState,

    /**
     * 获取需求详情
     * @param id 需求id
     */
    getDemandDetail: async (id: string) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          id: id,
        };
        const res = await fetchDemandDetail(requestData);

        set((state) => {
          state.demandDetail = res.data;
        });
      } catch (error) {
        console.log('获取需求详情失败', error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    /**
     * 点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleLikeOrDislike: async (demandId: string, type: string, status: string) => {
      try {
        const result = await operateDemand({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.demandDetail;
            if (item) {
              if (type === 'LIKE') {
                // 如果之前点踩了，先取消点踩
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                // 如果之前点赞了，先取消点赞
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }
          });
          // 更新demandList中的对应项
          demandListStore.setState((listState) => {
            const index = listState.demandList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.demandList[index];
              if (type === 'LIKE') {
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }
          });
          // 更新searchList中的对应项
          searchStore.setState((listState) => {
            const index = listState.searchList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.searchList[index];
              if (type === 'LIKE') {
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }
          });
          // 更新myColletList中的对应项
          myColletionStore.setState((listState) => {
            const index = listState.myColletList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.myColletList[index];
              if (type === 'LIKE') {
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleCancelLikeOrDislike: async (demandId: string, type: string) => {
      try {
        const result = await cancelOperateDemand({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.demandDetail;
            if (item) {
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
          // 更新demandList中的对应项
          demandListStore.setState((listState) => {
            const index = listState.demandList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.demandList[index];
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
          // 更新searchList中的对应项
          searchStore.setState((listState) => {
            const index = listState.searchList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.searchList[index];
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
          // 更新myColletList中的对应项
          myColletionStore.setState((listState) => {
            const index = listState.myColletList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.myColletList[index];
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 收藏
     */
    handleCollect: async (demandId: string, type: string, status: string) => {
      try {
        const result = await operateCollect({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.demandDetail;
            if (item) {
              if (type === 'COLLECT' || type === 'collection') {
                item.collectCount = (item.collectCount || 0) + 1;
                item.collect = true;
                console.log('handleCollect success');
              }
            }
          });
          // 更新demandList中的对应项
          demandListStore.setState((listState) => {
            const index = listState.demandList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.demandList[index];
              if (type === 'COLLECT' || type === 'collection') {
                item.collectCount = (item.collectCount || 0) + 1;
                item.collect = true;
              }
            }
          });
          // 更新searchList中的对应项
          searchStore.setState((listState) => {
            const index = listState.searchList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.searchList[index];
              if (type === 'COLLECT' || type === 'collection') {
                item.collectCount = (item.collectCount || 0) + 1;
                item.collect = true;
              }
            }
          });
          // 更新myColletList中的对应项
          myColletionStore.setState((listState) => {
            const index = listState.myColletList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.myColletList[index];
              if (type === 'COLLECT' || type === 'collection') {
                item.collectCount = (item.collectCount || 0) + 1;
                item.collect = true;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消收藏
     */
    handleCancelCollect: async (demandId: string) => {
      try {
        const result = await operateCancelCollect({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.demandDetail;
            if (item) {
              item.collectCount = (item.collectCount || 0) - 1;
              item.collect = false;
              console.log('handleCancelCollect success');
            }
          });
          // 更新demandList中的对应项
          demandListStore.setState((listState) => {
            const index = listState.demandList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.demandList[index];
              item.collectCount = (item.collectCount || 0) - 1;
              item.collect = false;
            }
          });
          // 更新searchList中的对应项
          searchStore.setState((listState) => {
            const index = listState.searchList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.searchList[index];
              item.collectCount = (item.collectCount || 0) - 1;
              item.collect = false;
            }
          });
          // 更新myColletList中的对应项
          myColletionStore.setState((listState) => {
            const index = listState.myColletList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.myColletList[index];
              item.collectCount = (item.collectCount || 0) - 1;
              item.collect = false;
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    clear() {
      set((state) => {
        state.demandDetail = {};
        state.isDataLoaded = true;
      });
    },
  })),
);
